//app.js
var auth = require('./utils/auth.js')
var mbrService = require('./api/memberService.js')

App({

  onLaunch: function () {
    this.refreshAccessToken();

    // 取当前用户    
    this.globalData.userInfo = auth.getUser();

  },
  onShow: function (options) {
    // Do something when show.
    console.log(options)
  },

  /**
   * 准备刷新令牌
   */
  refreshAccessToken() {
    var tokens = auth.getTokens();
    if (!tokens || !tokens.expiresTo) {
      console.log("当前用户未登录，请先登录")
      return;
    }

    // 如果refresh token也过期，就不再刷新令牌了
    if (tokens.refreshExpiresTo < new Date().getTime()) {
      console.log("刷新令牌已经过期，请重新登录")
      return
    }

    // 刷新令牌时间，提前30分钟
    var expiresIn = tokens.expiresTo - new Date().getTime() - 60 * 10 * 1000;
    expiresIn = expiresIn <= 0 ? 1000 : expiresIn;
    setTimeout(function () {
      // 准备刷新令牌
      mbrService.refreshToken(tokens.refreshToken)
        .then(data => {
          auth.setTokens(data)
        })
        .catch(err => {
          console.log(err)
        })
    }, expiresIn);
  },
  globalData: {
    userInfo: null,
    addressInfo: null,
    storeInfo: null,
    servicePhone: '4006-128-227'
  }
})